package com.hospital.hospitalserver.service;

import com.hospital.hospitalserver.entity.FinanceDetail;
import com.hospital.hospitalserver.entity.UserInfo;
import com.hospital.hospitalserver.entity.Vo.Finance;
import com.hospital.hospitalserver.mapper.DepartmentMapper;
import com.hospital.hospitalserver.mapper.FinanceMapper;
import com.hospital.hospitalserver.mapper.UserMapper;
import com.hospital.hospitalserver.util.EncryptHelper;
import com.hospital.hospitalserver.util.Pager;
import com.hospital.hospitalserver.util.PagerData;
import com.hospital.hospitalserver.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 财务人员相关实现方法
 * */
@Service
@RequiredArgsConstructor
public class FinanceService {
    private final FinanceMapper financeMapper;
    private final UserMapper userMapper;
    private final DepartmentMapper departmentMapper;

    /**
     * 新增财务人员
     * 添加事务处理，执行有错误回滚操作
     * */
    @Transactional(rollbackFor = Exception.class)
    public Response addFinance(FinanceDetail finance){
        // 1. 判断添加的账户是否存在重复
        UserInfo u = userMapper.findUserByUsername(finance);
        if(u!=null){
            return Response.error("账户名已存在");
        }

        // 2. 设置默认角色（例如财务人员角色 role_id = 5）
        finance.setRole_id(5);
        finance.setIs_active(1); // 默认激活
        String encryptedPassword = EncryptHelper.SHA(finance.getUserpass());
        finance.setUserpass(encryptedPassword);

        // 3. 添加用户，此时 finance 对象的 user_id 会被自动填充
        Integer addCount = userMapper.addUser(finance);
        if(addCount==0){
            return Response.error("用户添加失败");
        }

        // 4. 此时 finance.getUser_id() 已经包含新生成的 user_id
        finance.setFinance_id(finance.getUser_id());

        // 5. 添加财务人员详细信息
        Integer count = financeMapper.addFinance(finance);
        if(count>0){
            //添加成功则更新对应科室财务人员总数
            departmentMapper.UpdateAddFinanceCountByDepartmentId(finance.getDepartment_id());
            return Response.success();
        }else {
            return Response.error("财务人员信息添加失败");
        }
    }

    /**
     * 编辑医生信息
     * 添加事务处理，执行有错误回滚操作
     * */
    @Transactional(rollbackFor = Exception.class)
    public Response editFinance(FinanceDetail finance){
        // 1.取出财务人员数据信息
        Finance financeInfo = financeMapper.findByFinanceId(finance.getFinance_id());

        Integer counts = financeMapper.editFinance(finance);
        if(counts>0){
            //编辑成功之后判断是否更换了科室，如果更换科室要同步更新各个科室的财务人员人数
            // 2. 比对科室信息是否有修改
            if(!finance.getDepartment_id().equals(financeInfo.getDepartment_id())){
                //变更科室
                //减少原科室财务人员人数
                departmentMapper.UpdateDeleteFinanceCountByDepartmentId(financeInfo.getDepartment_id());
                //增加新科室财务人员人数
                departmentMapper.UpdateAddFinanceCountByDepartmentId(finance.getDepartment_id());
            }
            return Response.success();
        }
        return  Response.error();
    }

    /**
     * 分页功能
     * 根据搜索条件查询财务人员数据总数
     * */
    private Integer getFinanceCountBySearch(Pager pager){
        return financeMapper.getFinanceCountBySearch(pager);
    }

    /**
     * 计算分页
     * */
    private Integer getFinancePageTotalBySearch(Pager pager){
        Integer financeTotalCounts = getFinanceCountBySearch(pager);
        Integer pageTotal = 1; //设置初始页码为1
        //数据总条数除以pageSize每页显示条数，如取余数求模，如果有余数，页码+1
        //如果可以整除，则页码等于数据总数除以pageSize
        pageTotal = financeTotalCounts/pager.getPageSize();
        if(financeTotalCounts%pager.getPageSize()>0){
            pageTotal += 1;
        }
        return pageTotal;
    }

    /**
     * 分页功能
     * 根据搜索条件查询财务人员分页数据
     * */
    List<Finance> getFinanceMapperDataBySearch(Pager pager){
        Integer currentPage = pager.getCurrentPage();
        Integer startIndex = (currentPage -1)*pager.getPageSize();
        pager.setStartIndex(startIndex);
        return financeMapper.getFinanceMapperDataBySearch(pager);
    }

    /**
     * 分页功能
     * 装载财务人员分页数据信息给前端API
     * */
    public Response getFinancePagerDataBySearch(Pager pager){
        PagerData pagerData = new PagerData();
        pagerData.setTotal(getFinanceCountBySearch(pager));
        pagerData.setPageTotal(getFinancePageTotalBySearch(pager));
        pagerData.setData(getFinanceMapperDataBySearch(pager));
        return Response.success(pagerData);
    }

    /**
     * 获取财务人员列表数据
     * 用于检索
     * */
    public Response getFinanceList(){
        return Response.success(financeMapper.getFinanceList());
    }
}
